
 /**
  * 时间戳返回为 D天 hh:mm:ss
  * @param {Number} difference 时间戳
  */
const parseTimestamp = difference=>{
  let daysMs = 24*60*60*1000
  let hoursMs = 60*60*1000
  let minuteMs = 60*1000
  let secondMs = 1000
  let days = ~~(difference / daysMs)
  let leftMs = difference % daysMs
  let hours = ~~(leftMs / hoursMs)
  leftMs = difference % hoursMs
  let minutes = ~~(leftMs / minuteMs)
  leftMs = leftMs % minuteMs
  let seconds = ~~(leftMs / secondMs)
  if(hours<10) hours = '0' + hours
  if(minutes<10) minutes = '0' + minutes
  if(seconds<10) seconds = '0' + seconds
  return `${days}天 ${hours}:${minutes}:${seconds}`
}


/**
 * 返回目标时间戳（未来）距当前的格式化时间
 * @param {Number} timestamp 
 */
const parseTdTimestamp = timestamp => {
  const now = new Date().getTime()
  const difference = timestamp - now 
  let timestring = false
  if(difference > 0) {
    timestring = parseTimestamp(timestamp - now)
  }
  return timestring
}


/**
 * promise节流函数
 * @param {*} foo 
 * @param {Number} 延迟resolved时间
 */
const only = function (foo, delay=0){
  var isResolved = true
  return function(){
      const args = [...arguments];
      if(isResolved) {
          return new Promise((resolve, reject)=>{
              isResolved = false
              foo.apply(this,args).then(res=>{
                  if(!delay) {
                      resolve(res);
                      isResolved=true;
                  }else {
                      setTimeout(()=>{
                          resolve(res);
                          isResolved=true; 
                      },delay)
                  }
                   
              }).catch(e=>{reject(e);isResolved=true;})
          })
      }else {
        return Promise.reject('ERROR_PROMISE_LOADING')
      }
  }
}

module.exports = {parseTimestamp,parseTdTimestamp,only}